package com.dsteiner.xelavos.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import com.dsteiner.widgets.client.Widgets.IFlowPanel;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.xelavos.client.ChangeImageWidget.ChangeImageModel;
import com.dsteiner.xelavos.client.controller.CreateObjectController.ImageSuggestions;
import com.dsteiner.xelavos.client.resources.XelavosResources;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;

public class ChangeImageController {

	private ChangeImageModel changeImageModel;
	private IFlowPanel imagePanel;
	private IFlowPanel imageContentPanel;

	public void registerChangeImageWidget(ILazyWidget changeImageWidget) {
		changeImageWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				updateImagePanelVisibility();
				updateImagePanel();
			}
		});
	}

	public void registerChangeImageModel(ChangeImageModel changeImageModel) {
		this.changeImageModel = changeImageModel;
		changeImageModel.addPropertyChangeListener("imageUrls", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateImagePanelVisibility();
				updateImagePanel();
			}
		});
	}

	private void updateImagePanelVisibility() {
		List<ImageSuggestions> imageUrls = changeImageModel.getImageUrls();
		imagePanel.setVisible(imageUrls != null && !imageUrls.isEmpty());
	}

	private void updateImagePanel() {
		List<ImageSuggestions> imageUrls = changeImageModel.getImageUrls();
		imageContentPanel.clear();
		for (final ImageSuggestions imageSuggestions : imageUrls) {
			FlowPanel flowPanel = new FlowPanel();
			HTML imageSuggestionHtml = new HTML("Sugerencias para <strong>" + imageSuggestions.getText()+"</strong>");
			imageSuggestionHtml.addStyleName(XelavosResources.INSTANCE.css().imageSuggestionHtml());
			flowPanel.add(imageSuggestionHtml);
			for (final String imageUrl : imageSuggestions.getImageUrls()) {
				Image image = new Image(imageUrl);
				image.addClickHandler(new ClickHandler(){
					public void onClick(ClickEvent event) {
						changeImageModel.setSelectedImageUrl(imageUrl);
					}
				});
				flowPanel.add(image);
			}
			imageContentPanel.add(flowPanel);
		}
	}

	public void registerImagePanel(IFlowPanel imagePanel) {
		this.imagePanel = imagePanel;
	}

	public void registerImageContentPanel(IFlowPanel imageContentPanel) {
		this.imageContentPanel = imageContentPanel;
	}
}